<?php

namespace app\controller;

use app\BaseController;
use think\facade\View;
use think\facade\Request;
use think\facade\Session;
use app\model\Site;
use app\utils\Utils;
use think\facade\Cache;
use app\model\User;
use app\model\Log;
use think\facade\Db;
use think\facade\Cookie;

class Login extends BaseController
{
    static public function index() // 页面
    {

        $email = Session::get('email', '');
        $pw = Session::get('password', '');
        $my_user_info = Utils::user($email, $pw);

        return View::fetch(Site::get("template") . '/login', [
            'img' => Site::get("img"),
            'title' => Site::get("title"),
            'user_name' => $my_user_info["name"],
            'user_email' => $my_user_info["email"],
            'user_img' => $my_user_info["img"],
            'user_id' => $my_user_info["id"],
            'logo' => Site::get("logo"),
            'about' => Site::get('about'),
            'header' => Site::get("header"),
            'footer' => Site::get("footer"),
            'footer_about' => Site::get("footer_about"),
            'footer_list' => Site::get('footer_list'),
            'navitems' => Site::get('navitems')
        ]);
    }

    static public function login() // API
    {
        $email = Request::post('email', false);
        $pw = Request::post('pw', false);

        if (!$email || !$pw) {
            return json(['code' => 404, 'msg' => '缺少参数']);
        }

        // 检查登录频率限制
        $lastLogin = Cache::get($email);
        if ($lastLogin && $lastLogin + 10 > time()) {
            return json(['code' => 403, 'msg' => '请稍等一会在登录哦~']);
        }

        // 更新登录时间缓存
        Cache::set($email, time(), 15);

        // 查找用户（支持邮箱或用户名）
        $user = User::where('email', $email)->find() ?: User::where('name', $email)->find();
        if (!$user || $user['password'] !== hash('sha256', $pw)) {
            return json(['code' => 403, 'msg' => '账号不存在或密码错误']);
        }

        // 检查账号是否被冻结
        if (Cache::get(md5('uid_' . $user['id']))) {
            return json(['code' => 403, 'msg' => '账号被冻结']);
        }

        // 设置 session
        Session::set('email', $user['email']);
        Session::set('password', $user['password']);
        Session::set('ua', Request::header('user-agent'));

        // 更新或插入 token
        $sessionId = Cookie::get('PHPSESSID');
        $tokenData = [
            'time' => time(),
            'ip' => Utils::getIp(),
            'ua' => Request::header('user-agent'),
            'token' => $sessionId,
            'user_id' => $user['id'],
            'bad' => 0
        ];

        Db::name('site_token')
            ->where('token', $sessionId)
            ->find() ?
            Db::name('site_token')->where('token', $sessionId)->update($tokenData) :
            Db::name('site_token')->insert($tokenData);

        return json(['code' => 200, 'msg' => '登录成功']);
    }
}
